package com.kyzh.core.pager.home


import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.blankj.utilcode.util.PermissionUtils
import com.google.android.material.badge.BadgeDrawable
import com.google.android.material.badge.BadgeUtils
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.gushenge.atools.util.getStatusBarHeight
import com.gushenge.atools.util.setHeight
import com.gushenge.core.base.fragment.BaseFragment
import com.gushenge.core.beans.IndexTop
import com.gushenge.core.beans.UserInfo
import com.gushenge.core.dao.MMKVConsts
import com.gushenge.core.impls.UserImpl
import com.gushenge.core.listeners.ResultListener
import com.gushenge.core.requests.UserRequest
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.kyzh.core.R
import com.kyzh.core.activities.NoticeActivity
import com.kyzh.core.adapters.v3.HomeTopTabAdapter
import com.kyzh.core.pager.home.homesearch.SearchActivity
import com.kyzh.core.uis.alert
import com.kyzh.core.utils.loadImage
import com.kyzh.core.utils.setVisibility
import com.kyzh.core.utils.startLogin
import com.umeng.commonsdk.debug.E
import kotlinx.android.synthetic.main.frag_home_title.*
import kotlinx.android.synthetic.main.fragment_home.*
import org.jetbrains.anko.support.v4.dip
import org.jetbrains.anko.support.v4.startActivity
import org.jetbrains.anko.textColor
import java.util.*


/**
 * A simple [Fragment] subclass.
 *
 */
class HomeFragment : BaseFragment() {


    val titles = arrayListOf<IndexTop>()
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_home, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()

    }

    private fun initView() {
        initTitles()
        val adapter = HomeTopTabAdapter(this, titles)
        viewpager.adapter = adapter
        viewpager.currentItem = 0
        val mediator = TabLayoutMediator(tabLayout, viewpager) { tab, position ->
            tab.text = titles[position].name
        }
        mediator.attach()
        try {
            val recyclerViewField = ViewPager2::class.java.getDeclaredField("mRecyclerView")
            recyclerViewField.isAccessible = true
            val recyclerView = recyclerViewField.get(viewpager) as RecyclerView

            val touchSlopField = RecyclerView::class.java.getDeclaredField("mTouchSlop")
            touchSlopField.isAccessible = true
            val touchSlop = touchSlopField.get(recyclerView) as Int
            touchSlopField.set(recyclerView, touchSlop * 8)

        } catch (e: Exception) {

        }

        val textView: TextView = View.inflate(requireContext(), R.layout.tab_text, null) as TextView
        textView.textColor = Color.WHITE
        textView.text = tabLayout.getTabAt(0)?.text
        tabLayout.getTabAt(0)?.customView = textView
        tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                val textView1: TextView =
                    View.inflate(requireContext(), R.layout.tab_text, null) as TextView
                textView1.text = tab?.text
                textView1.textColor = Color.WHITE
                tab?.customView = textView1
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
                tab?.customView = null
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {

            }
        })

    }

    private fun initTitles() {
        title.setHeight(dip(44) + requireActivity().getStatusBarHeight())
        search.setOnClickListener { startActivity<SearchActivity>() }
        titles.clear()
        initFace()
        icon.setOnClickListener {
            if (startLogin()) {
//                startActivity<UserDataActivity>()
                val mainActivity = requireActivity() as MainActivity
                mainActivity.me()
            }
        }
        download.setOnClickListener {
            if (startLogin()) {
                if (!XXPermissions.isGranted(
                        requireContext(),
                        Permission.READ_EXTERNAL_STORAGE,
                        Permission.CAMERA
                    )
                ) {
                    XXPermissions.with(requireActivity()).permission(
                        Permission.READ_EXTERNAL_STORAGE,
                        Permission.CAMERA
                    ).request(object : OnPermissionCallback {
                        override fun onGranted(permissions: MutableList<String>?, all: Boolean) {
//                            ScanUtil.startScan(
//                                requireActivity(),
//                                1000,
//                                HmsScanAnalyzerOptions.Creator()
//                                    .setHmsScanTypes(HmsScan.QRCODE_SCAN_TYPE)
//                                    .create()
//                            )
                            ScanActivity.start(requireContext())
                        }

                        override fun onDenied(permissions: MutableList<String>?, never: Boolean) {
                            super.onDenied(permissions, never)
                            requireActivity().alert("申请权限", "需要摄像头及存储权限才能使用此功能", "去设置", "取消", {
                                PermissionUtils.launchAppDetailsSettings()
                            }, { })
                        }
                    })
                } else {
                    ScanActivity.start(requireContext())
                }
            }

        }
        message.setOnClickListener {
            if (startLogin()) {
                startActivity<NoticeActivity>()
            }
        }
        kotlin.runCatching {
            val map = Gson().fromJson<ArrayList<IndexTop>>(MMKVConsts.index,
                object : TypeToken<ArrayList<IndexTop>>() {
                }.type)
            for (i in map) {
                if (i.status) {
                    titles.add(i)
                }
            }
        }

        if (titles.size == 2) {
            download.visibility = View.GONE
        } else {
            download.visibility = View.VISIBLE
        }


    }

    override fun onResume() {
        super.onResume()
        initFace()
    }

    private fun initFace() {
        UserRequest.hasNewMessage {
            ivDian.setVisibility(this)
        }
        UserImpl.userInfo(object : ResultListener {
            override fun success(user: Any) {
                icon.loadImage(requireActivity(), (user as UserInfo).face)
            }

            override fun error(error: String) {
                icon.setImageResource(R.drawable.logo_new)
            }
        })
    }

    override fun onHiddenChanged(hidden: Boolean) {
        initFace()
    }
}
